package com.visikard.ui.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.DeleteCouponAsyncTask;
import com.visikard.asynctask.GetListCouponTask;
import com.visikard.item.CouponBuilderItem;
import com.visikard.response.DeleteCouponResponse;
import com.visikard.response.GetListCouponResponse;
import com.visikard.ui.R;
import com.visikard.ui.activity.CouponBuilderActivityV3;
import com.visikard.ui.activity.MerchantHomeActivity;
import com.visikard.ui.activity.MerchantHomeActivity.IDeleteCoupon;
import com.visikard.ui.adapter.ListCouponAdapter;
import com.visikard.utility.Utils;

public class ListCouponFragment extends BaseFragment implements IDeleteCoupon {
	// setArguments-->onAttach-->onCreate-->onCreateView-->onActivityCreated
	// onDestroyView-->onDestroy-->onDetach

	private MerchantHomeActivity me;
	private View mView;

	private Button mButton_back, mButton_create;
	private ImageButton mButton_filter, mButton_search;
	private ListView mListView;

	private ListCouponAdapter mAdapter;

	private ListView mPopup;

	private RelativeLayout mSearchBar;

	private EditText mEditText_search;
	private ImageButton mButton_close_search;

	private BaseTask mAsyncTask;

	private final int CREATE_COUPON_REQUEST_CODE = 111;

	private IDeleteCoupon mCallback;
	private ArrayList<CouponBuilderItem> arrayList = new ArrayList<CouponBuilderItem>();
	private CouponBuilderItem mDelete;

	private void initControls(View view) {
		mButton_back = (Button) view.findViewById(R.id.btn_back);
		mButton_create = (Button) view.findViewById(R.id.btn_create);

		mButton_filter = (ImageButton) view.findViewById(R.id.btn_filter_coupon);
		mButton_search = (ImageButton) view.findViewById(R.id.btn_search_coupon);

		mListView = (ListView) view.findViewById(R.id.list_coupons_builder);

		mButton_back.setOnClickListener(new MyOnClickListenerClass());
		mButton_create.setOnClickListener(new MyOnClickListenerClass());
		mButton_filter.setOnClickListener(new MyOnClickListenerClass());
		mButton_search.setOnClickListener(new MyOnClickListenerClass());

		mPopup = (ListView) view.findViewById(R.id.popup_filter);
		mPopup.setVisibility(View.GONE);
		mPopup.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int positon, long arg3) {
				// TODO Auto-generated method stub
				mPopup.setVisibility(View.GONE);

			}
		});
		mSearchBar = (RelativeLayout) view.findViewById(R.id.search_bar);

		mEditText_search = (EditText) view.findViewById(R.id.coupon_search);
		mEditText_search.addTextChangedListener(new MyOnTextChangedListener());

		mButton_close_search = (ImageButton) view.findViewById(R.id.image_btn_close);
		mButton_close_search.setOnClickListener(new MyOnClickListenerClass());

	}

	@Override
	public void setArguments(Bundle args) {
		// TODO Auto-generated method stub
		super.setArguments(args);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		try {
			mCallback = (IDeleteCoupon) this;
		}
		catch (ClassCastException e) {
			throw new ClassCastException(activity.toString());
		}
	}

	@Override
	public void onCreate(Bundle bundle) {
		// TODO Auto-generated method stub
		super.onCreate(bundle);

		me = (MerchantHomeActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.list_coupon_fragment, null);
		initControls(mView);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		callApiGetListCoupon();
	}

	private class MyOnClickListenerClass implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == mButton_back) {

				me.showExitDialog();
			}
			else if (v == mButton_create) {

				Intent intent = new Intent(me, CouponBuilderActivityV3.class);
				startActivityForResult(intent, CREATE_COUPON_REQUEST_CODE);
			}
			else if (v == mButton_filter) {
				mSearchBar.setVisibility(View.GONE);
				String[] values = new String[] { "All", "Expired", "Active" };
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
						android.R.layout.simple_list_item_1, android.R.id.text1, values);
				mPopup.setAdapter(adapter);
				mPopup.bringToFront();
				showOrHide(mPopup);

			}
			else if (v == mButton_search) {

				mPopup.setVisibility(View.GONE);
				mSearchBar.bringToFront();

				showOrHide(mSearchBar);
				mEditText_search.setText("");
			}
			else if (v == mButton_close_search) {
				mEditText_search.setText("");
			}
		}

	}

	private class MyOnTextChangedListener implements TextWatcher {

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			mAdapter.getFilter().filter(s.toString());
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub

		}

	}

	private void callApiGetListCoupon() {

		mAsyncTask = new GetListCouponTask(mHandler);
		long fkUser = VKRegApplication.merchantAccountObj.getIdUsers();
		String timeZone = Utils.getTimeZoneString();
		mAsyncTask.execute(String.valueOf(fkUser), timeZone, String.valueOf(1), String.valueOf(50));
	}

	private void callApiDeleteCoupon(CouponBuilderItem item) {

		mAsyncTask = new DeleteCouponAsyncTask(mHandler);
		mAsyncTask.execute(String.valueOf(item.getIdCoupons()));
	}

	@Override
	protected boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		if (getActivity() == null)
			return false;
		switch (msg.what) {

			case UIMessage.MSG_GET_LIST_COUPON_FINISH:
				GetListCouponResponse result = (GetListCouponResponse) msg.obj;

				if (result != null) {
					if (result.getErrorCode() == 0) {
						ArrayList<CouponBuilderItem> list = result.getList();

						if (list != null) {
							arrayList = list;
							mAdapter = new ListCouponAdapter(me, list, mCallback);
							mListView.setAdapter(mAdapter);

						}
						else {
							Utils.showToast(me, me.getString(R.string.unknown_problem));

						}
					}
					else if (result.getErrorCode() == -2) {
						Log.e("CreateCoupon>", result.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.network_problem));

					}
					else if (result.getErrorCode() == -3) {
						Log.e("CreateCoupon>", result.getErrorMsg());

					}
					else if (result.getErrorCode() == -4) {
						Log.e("CreateCoupon>", result.getErrorMsg());

					}
					else {
						Log.e("CreateCoupon>", result.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.unknown_problem));

					}

				}
				return true;
			case UIMessage.MSG_DELETE_COUPON_FINISH:
				DeleteCouponResponse result_delete = (DeleteCouponResponse) msg.obj;

				if (result_delete != null) {
					if (result_delete.getErrorCode() == 0) {
						String status = result_delete.getStatus();
						Log.e("DeleteCouponSTATUS>", status);

						if (status.equals("OK")) {
							arrayList.remove(mDelete);
							mAdapter.notifyDataSetChanged();
							Utils.showToast(me, me.getString(R.string.alert_delete_coupons_success));
						}
						else {
							Utils.showToast(me, me.getString(R.string.alert_delete_coupons_failed));
						}

					}
					else if (result_delete.getErrorCode() == -2) {
						Log.e("DeleteCoupon>", result_delete.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.network_problem));
					}
					else if (result_delete.getErrorCode() == -3) {
						Log.e("DeleteCoupon>", result_delete.getErrorMsg());

					}
					else if (result_delete.getErrorCode() == -4) {
						Log.e("DeleteCoupon>", result_delete.getErrorMsg());

					}
					else {
						Log.e("DeleteCoupon>", result_delete.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.unknown_problem));

					}

				}
				return true;
		}
		return super.handleMessage(msg);
	}

	public static void showOrHide(View view) {
		if (view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE) {
			view.setVisibility(View.VISIBLE);
		}
		else {
			view.setVisibility(View.GONE);
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == me.RESULT_OK) {
			if (requestCode == CREATE_COUPON_REQUEST_CODE) {
				callApiGetListCoupon();
			}

		}
	}

	/**
	 * Destroy
	 */
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
	}

	@Override
	public void onDeleteCoupon(CouponBuilderItem item) {
		// TODO Auto-generated method stub
		callApiDeleteCoupon(item);
		mDelete = item;
	}

}
